package com.fox.alibabaaidemo.controller;


import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
public class ChatModelController {
    //ChatModel是对话模型，真正与大模型交互的类，之前用的是ChatClient其实是ChatModel的封装
    //ChatModel支持纯文本输入和纯文本输出
    //ImageModel接收用户文本输入，输出图片
    //AudioModel接收用户文本输入，输出音频
    private final ChatModel chatModel;

    //指定了大模型是dashscopeChatModel
    public ChatModelController(@Qualifier("dashscopeChatModel") ChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @RequestMapping("/chat2")
    public String chat2(String input) {
        //这里不像ImageModel一样要指定具体大模型，是因为有默认的大模型
        DashScopeChatOptions options = DashScopeChatOptions.builder()
                .withTemperature(0.9)//设置温度为0.9，作用是控制生成文本的多样性（0 - 2），温度越高，创建性和随机性越高，温度越低，确定性越高
                .withMaxToken(1500)//设置上下文最大长度为1500
           //     .withTopP(0.01)
                .build();

        Prompt prompt = new Prompt(input, options);
        ChatResponse response = chatModel.call(prompt);
        //ChatResponse response = chatModel.call(new Prompt(input));
        return response.getResult().getOutput().getText();
    }


    @RequestMapping("/streamChat")
    public Flux<String> streamChat(String input, HttpServletResponse response) throws IOException {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        return chatModel.stream(input);
    }


}